package com.zhiziai.aiproxy.controller;

import com.zhiziai.aiproxy.constants.BusinessCode;
import com.zhiziai.aiproxy.dto.JsonVo;
import com.zhiziai.aiproxy.service.OpenAIServiceImpl;
import com.zhiziai.aiproxy.utils.OpenAIUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;


@Controller
@Slf4j
@RequestMapping("/openai")
public class OpenAIController {

    @Autowired
    private OpenAIServiceImpl searchService;

    @RequestMapping("/question")
    @ResponseBody
    public Object question(String msg) {
        try {
            return new JsonVo(BusinessCode.SUCCESS.getValue(), BusinessCode.SUCCESS.getMsg(), OpenAIUtil.testChatGpt(msg));
        } catch (Exception e) {
            return new JsonVo(BusinessCode.ERROR.getValue(), e.getMessage());
        }
    }

    @RequestMapping("/questionEncrypt")
    @ResponseBody
    public Object questionEncrypt(String msg,String sign) {
        try {
            return new JsonVo(BusinessCode.SUCCESS.getValue(), BusinessCode.SUCCESS.getMsg(), searchService.encryptChat(msg,sign));
        } catch (Exception e) {
            return new JsonVo(BusinessCode.ERROR.getValue(), e.getMessage());
        }
    }

    @RequestMapping("/imgGenEncrypt")
    @ResponseBody
    public Object imgGenEncrypt(String prompt,Integer genNum, String resulotionRate, String sign ) {
        try {
            return new JsonVo(BusinessCode.SUCCESS.getValue(), BusinessCode.SUCCESS.getMsg(), searchService.encryptImgGen(prompt,genNum,resulotionRate,sign));
        } catch (Exception e) {
            return new JsonVo(BusinessCode.ERROR.getValue(), e.getMessage());
        }
    }

    @RequestMapping("/imgEditEncrypt")
    @ResponseBody
    public Object imgEditEncrypt(String prompt, Integer genNum, String resulotionRate, File image, File mask, String sign ) {
        try {
            return new JsonVo(BusinessCode.SUCCESS.getValue(), BusinessCode.SUCCESS.getMsg(), searchService.encryptImgEdit(prompt,genNum,resulotionRate,image,mask,sign));
        } catch (Exception e) {
            return new JsonVo(BusinessCode.ERROR.getValue(), e.getMessage());
        }
    }

    @RequestMapping("/audioTranscriptionsEncrypt")
    @ResponseBody
    public Object audioTranscriptionsEncrypt(@RequestParam("file") MultipartFile file, String randomSalt, String language,String prompt, String temperature, String sign) {
        try {
            return new JsonVo(BusinessCode.SUCCESS.getValue(), BusinessCode.SUCCESS.getMsg(), searchService.audioTranscriptionsEncrypt(file,prompt,language,temperature,randomSalt,sign));
        } catch (Exception e) {
            return new JsonVo(BusinessCode.ERROR.getValue(), e.getMessage());
        }
    }

//    @PostMapping("/wx/question")
//    @ResponseBody
//    public String replyUserMessage(ServletRequest request, ServletResponse response) {
//        try {
//            WxUserMessageModel wxUserMessageModel = resolveXmlData(request.getInputStream());
//            if (wxUserMessageModel != null) {
//                log.info("wxUserMessageModel {}", JSONObject.toJSONString(wxUserMessageModel));
//                if (redisTemplate.opsForValue().setIfAbsent("chat_lock", wxUserMessageModel.getMsgId(), 10, TimeUnit.SECONDS)) {
//                    WxUserMessageModel responseXmlData = new WxUserMessageModel();
//                    responseXmlData.setToUserName(wxUserMessageModel.getFromUserName());
//                    responseXmlData.setFromUserName(wxUserMessageModel.getToUserName());
//                    responseXmlData.setCreateTime(System.currentTimeMillis());
//                    responseXmlData.setMsgType("text");
//                    ChatGPTUtil.Msg msg = ChatGPTUtil.question(Arrays.asList(wxUserMessageModel.getContent()));
//                    if (msg != null && !StringUtils.isEmpty(msg.getContent())) {
//                        responseXmlData.setContent(msg.getContent().trim());
//                        XStream xstream = new XStream();
//                        xstream.processAnnotations(WxUserMessageModel.class);
//                        xstream.setClassLoader(WxUserMessageModel.class.getClassLoader());
//                        return StringEscapeUtils.unescapeXml(xstream.toXML(responseXmlData));
//                    }
//                }
//            }
//        } catch (Exception e) {
//            log.error("replyUserMessage is error ", e);
//        }
//        return "success";
//    }

//    /**
//     * 解析xml数据
//     *
//     * @param in 输入流
//     * @return 微信用户信息实体类
//     * @throws IOException
//     */
//    private WxUserMessageModel resolveXmlData(InputStream in) throws IOException {
//        String xmlData = IoUtil.read(in, "UTF-8");
//        Map<String, Object> map = XmlUtil.xmlToMap(xmlData);
//        return JSONObject.parseObject(JSONObject.toJSONString(map), WxUserMessageModel.class);
//    }

    //    /**
//     * 验证消息来自微信
//     * @return
//     * @throws
//     */
//    @RequestMapping("/wx/question")
//    @ResponseBody
//    public String wxQuestion(String signature,String timestamp,String nonce,String echostr ) {
//        List<String> list = new ArrayList<>();
//        // 配置上所填写的token
//        list.add("chatgpt");
//        list.add(timestamp);
//        list.add(nonce);
//        // 字典序排序
//        Collections.sort(list);
//        // 拼接
//        StringBuilder sb = new StringBuilder();
//        list.forEach(sb::append);
//        // sha1加密
//        String hashCode = DigestUtils.sha1DigestAsHex(sb.toString());
//        // 比对
//        if (StringUtils.equals(hashCode,signature)){
//            return echostr;
//        }else {
//            return "";
//        }
//    }


//    public static void main(String[] args) {
//        String xml = "<xml><ToUserName><![CDATA[gh_028459ec9c90]]></ToUserName>\n" +
//                "<FromUserName><![CDATA[o5t2W1JhOW95PRmcQ4Whov9kjLUY]]></FromUserName>\n" +
//                "<CreateTime>1678269165</CreateTime>\n" +
//                "<MsgType><![CDATA[text]]></MsgType>\n" +
//                "<Content><![CDATA[叮当的]]></Content>\n" +
//                "<MsgId>24027035606221714</MsgId>\n" +
//                "</xml>";
//        Map<String, Object> map = XmlUtil.xmlToMap(xml);
//        WxUserMessageModel wxUserMessageModel = JSONObject.parseObject(JSONObject.toJSONString(map), WxUserMessageModel.class);
//        XStream xstream = new XStream();
//        xstream.processAnnotations(WxUserMessageModel.class);
//        xstream.setClassLoader(WxUserMessageModel.class.getClassLoader());
//
//        String transXml = StringEscapeUtils.unescapeXml(xstream.toXML(wxUserMessageModel));
//    }
}
